package com.yihubang.taobaokotlin.presenter.impl

import android.util.Log
import com.yihubang.taobaokotlin.interfaces.ICategoryPageCallback
import com.yihubang.taobaokotlin.model.Api
import com.yihubang.taobaokotlin.model.HomePagerContent
import com.yihubang.taobaokotlin.presenter.ICategoryPagerPresenter
import com.yihubang.taobaokotlin.utils.RetrofitManage
import com.yihubang.taobaokotlin.utils.UrlUtils
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.net.HttpURLConnection

/*
 * class title: 
 * Author by RenChunLin, Email 18957806320@163.com, Date on 2021/5/11.
 * PS: Not easy to write code, please indicate.
 */
object CategoryPagePresenterImpl : ICategoryPagerPresenter {

    /**
     * 创建可变list，保存TabLayout+ViewPager中的每一个Fragment
     */
    val callbacks = mutableListOf<ICategoryPageCallback>()

    /**
     * 保存每一个Fragment所对应的请求数据的当前页码
     * key Fragment对应的category id
     * value 分类列表的页码
     */
    val pageCode = HashMap<Int?, Int>()

    //默认页码
    const val DEFAULT_PAGE = 1

    var currentPage: Int = DEFAULT_PAGE

    override fun getContentByCategoryId(categoryId: Int?) {
        for (callback in callbacks) {
            if (callback.getCategoryId() == categoryId) {
                callback.onLoading()
            }
        }

        var getKey = pageCode[categoryId]
        if (getKey == null) {
            getKey = DEFAULT_PAGE
            pageCode[categoryId] = DEFAULT_PAGE
        }

        val createTask = createTask(categoryId, getKey)
        createTask.enqueue(object : Callback<HomePagerContent> {
            override fun onResponse(
                call: Call<HomePagerContent>,
                response: Response<HomePagerContent>
            ) {
                val code = response.code()
                if (code == HttpURLConnection.HTTP_OK) {
                    val body = response.body()
                    //把数据给ui
                    body?.let { handleHomePageContentResult(body, categoryId) }
                }
            }

            override fun onFailure(call: Call<HomePagerContent>, t: Throwable) {
                Log.i("chen", "onError: ${t.message}")
            }
        })
    }

    private fun handleHomePageContentResult(body: HomePagerContent, categoryId: Int?) {
        val datas = body.data
        for (callback in callbacks) {
            if (callback.getCategoryId() == categoryId) {
                if (callbacks.size == 0) {
                    callback.onEmpty()
                } else {
                    callback.onContentLoaded(datas)
                    val subList = datas.subList(datas.size - 5, datas.size)
                    callback.onLooperListLoadedList(subList)
                }
            }
        }
    }

    fun createTask(categoryId: Int?, pageCode: Int): Call<HomePagerContent> {
        val homePagerUrl = UrlUtils.createHomePagerUrl(categoryId, pageCode)
        //根据分类id去加载内容
        val retrofit = RetrofitManage.getRetrofit()
        val api = retrofit.create(Api::class.java)
        return api.getHomePageContent(homePagerUrl)
    }

    //加载更多数据
    override fun getLoadMore(categoryId: Int?) {
        //拿到当前页
        if (pageCode[categoryId] == null) {
            currentPage = DEFAULT_PAGE
        }
        //页码++
        currentPage++
        pageCode[categoryId] = currentPage
        //加载数据
        val createTask = createTask(categoryId, currentPage)
        createTask.enqueue(object : Callback<HomePagerContent> {
            override fun onResponse(
                call: Call<HomePagerContent>,
                response: Response<HomePagerContent>
            ) {
                //结果
                val code = response.code()
                if (code == HttpURLConnection.HTTP_OK) {
                    val body = response.body()
                    body?.let { handleLoaderResult(body, categoryId) }
                } else {
                    //请求失败
                    handleLoaderMoreError(categoryId)
                }
            }

            override fun onFailure(call: Call<HomePagerContent>, t: Throwable) {
                handleLoaderMoreError(categoryId)
            }
        })
    }

    private fun handleLoaderMoreError(categoryId: Int?) {
        currentPage--
        pageCode[categoryId] = currentPage
        for (callback in callbacks) {
            if (callback.getCategoryId() == categoryId) {
                callback.onLoaderMoreError()
            }
        }
    }

    private fun handleLoaderResult(body: HomePagerContent, categoryId: Int?) {
        for (callback in callbacks) {
            if (callback.getCategoryId() == categoryId) {
                if (body.data.size == 0) {
                    callback.onLoaderMoreEmpty()
                } else {
                    callback.onLoaderMoreLoaded(body.data)
                }
            }
        }
    }

    override fun registerViewCallback(callback: ICategoryPageCallback) {
        if (!callbacks.contains(callback)) {
            callbacks.add(callback)
        }
    }

    override fun unregisterViewCallback(callback: ICategoryPageCallback) {
        callbacks.remove(callback)
    }

}